package com.itheima.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.result.PageResult;
import com.itheima.common.result.Result;
import com.itheima.dto.SysUserDTO;
import com.itheima.dto.SysUserPageQueryDTO;
import com.itheima.mapper.SysRoleMapper;
import com.itheima.mapper.SysUserMapper;
import com.itheima.pojo.SysRole;
import com.itheima.pojo.SysUser;
import com.itheima.service.SysUserService;
import com.itheima.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 用户列表分页
     *
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> pageQuery(SysUserPageQueryDTO dto) {
//        1非空判断
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getLimit() == null) {
            dto.setLimit(10);
        }
        //2开始分页
        PageHelper.startPage(dto.getPage(), dto.getLimit());
        //3.根据条件查询用户列表调用mapper
        Page<SysUser> page = sysUserMapper.pageUser(dto);
        long total = page.getTotal();
        List<SysUser> sysUserList = page.getResult();
        List<SysUserVO> sysUserVOList = new ArrayList<>(sysUserList.size());

        sysUserList.forEach(sysUser -> {
            SysUserVO sysUserVO = new SysUserVO();
            BeanUtils.copyProperties(sysUser, sysUserVO);
            //从sysUser得到roleId
            String roleId = sysUser.getRoleId();
            //得到role的id集合
            List<String> roleNameList = new ArrayList<>();
//            Wrapper<SysRole> sysRoleWrapperr = new QueryWrapper<>();
            String[] split = roleId.substring(1, roleId.length() - 1).split(",");
            List<String> roleIdList = Arrays.stream(split).map(s -> s.replace("\"", "")).collect(Collectors.toList());
            for (String role : roleIdList) {
                SysRole sysRole = sysRoleMapper.selectById(role.trim());
                if (sysRole == null || sysRole.getName() == null || "".equals(sysRole.getName())) {
                    continue;
                }
                //得到role的名字
                String roleName = sysRole.getName();
                roleNameList.add(roleName);
            }
            sysUserVO.setRoleId(roleIdList.toString());
            sysUserVO.setRolename(roleNameList);
            sysUserVOList.add(sysUserVO);
        });

        //4.封装数据并返回
        int pages = page.getPages();
        PageResult pageResult = new PageResult();
        pageResult.setData(sysUserVOList);
        pageResult.setPageSize(dto.getLimit());
        pageResult.setTotalPages(pages);
        pageResult.setCount(total);
        pageResult.setCurrenPage(dto.getPage());


        return Result.success(pageResult);


    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(String id) {
        if (id == null) {
            return Result.error("id不存在");
        }
        SysUser sysUser = sysUserMapper.selectById(id);
        //修改删除标记为1
        sysUser.setDelFlag("1");
//        更新
        sysUserMapper.updateById(sysUser);
        return Result.success();
    }

    /**
     * 添加管理员
     *
     * @param dto
     * @return
     */
    @Override
    public Result addSysUser(SysUserDTO dto) {
        //新建一个sysUser用于接收dto数据
        SysUser sysUser = new SysUser();

        BeanUtils.copyProperties(dto, sysUser);
//        sysUser.setLoginName(dto.getLogin_name());
        log.info(sysUser.toString());
        //添加数据
        sysUser.setCreateDate(LocalDateTime.now());
        List roleId = dto.getRole_id();
        String string = roleId.toString();
        //把id更新一下
        sysUser.setRoleId(string);
        sysUserMapper.insert(sysUser);
        return Result.success();
    }

    /**
     * 根据id回显数据
     *
     * @param id
     * @return
     */
    @Override
    public Result<SysUserVO> getSysUserById(String id) {
        if (id == null) {
            return Result.error("未知错误");
        }
        SysUser sysUser = sysUserMapper.selectById(id);
        SysUserVO sysUserVO = new SysUserVO();


        //从sysUser得到roleId
        String roleId = sysUser.getRoleId();

        String[] split = roleId.substring(1, roleId.length() - 1).split(",");
        List<String> roleNameList = new ArrayList<>();
        List<String> roleIdList = Arrays.stream(split).map(s -> s.trim()).map(s -> s.replace("\"", "")).collect(Collectors.toList());
        for (String role : roleIdList) {

            SysRole sysRole = sysRoleMapper.selectById(role.trim());
            //得到role的名字
            String roleName = sysRole.getName();
            roleNameList.add(roleName);
        }
        BeanUtils.copyProperties(sysUser, sysUserVO);
        sysUserVO.setRoleIdList(roleIdList);

        return Result.success(sysUserVO);
    }

    /**
     * 更新sysUser
     *
     * @param map
     * @return
     */
    @Override
    public Result updateByMap(Map map) {
        SysUser sysUser = new SysUser();
        sysUser.setId((String) map.get("id"));
        sysUser.setStatus((Integer) map.get("status"));
//        sysUser.setDefaultData((String) map.get("default_data"));
//        log.info("默认参数",(String) map.get("default_data"));
        List<String> rolename = (List<String>) map.get("rolename");
        List<String> roleId = (List<String>) map.get("role_id");


        if (roleId != null && roleId.size() != 0) {
            sysUser.setPassword((String) map.get("password"));
            sysUser.setName((String) map.get("name"));
            sysUser.setEmail((String) map.get("email"));
            sysUser.setPhone((String) map.get("phone"));
            sysUser.setLoginName((String) map.get("login_name"));
            sysUser.setLoginIp((String) map.get("login_ip"));
            sysUser.setLoginDate((LocalDateTime) map.get("login_date"));
            sysUser.setUpdateDate(LocalDateTime.now());
            sysUser.setDelFlag((String) map.get("del_flag"));
            sysUser.setRoleId(roleId.toString());
        }
        sysUserMapper.updateById(sysUser);
        return Result.success();
    }

//   @Override
//   public Result sysUserUpdate(SysUserDTO sysUserDTO) {
//      Map map = new HashMap();
//        SysUser sysUser = new SysUser();
//       BeanUtils.copyProperties(sysUserDTO, sysUser);
//
//       //发现roleid字段拷贝失败,存在空格
//       sysUser.setStatus(sysUserDTO.getStatus());
//    sysUser.setRoleId(sysUserDTO.getRole_id().toString().trim());
//        sysUserMapper.updateById(sysUser);
//        return Result.success();
//
//
//  }


}
